package com.bankcomm.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import com.bankcomm.BankcommApplication;
import com.bankcomm.location.BaiduLocation;
import com.bankcomm.ui.BCMBranchBankActivity;
import com.bankcomm.ui.BOCMainHome;
import com.bankcomm.ui.BOCPushMessage;
import com.bankcomm.ui.BOCWebViewActivity;
import com.bankcomm.ui.BOC_SpecialShop_main_Activity;
import com.bankcomm.ui.BaseViewCopy;
import com.bankcomm.ui.EMPView;
import com.bankcomm.ui.LocationServiceActivity;
import com.bankcomm.ui.views.BCMHomeView;
import com.bankcomm.ui.views.DataStorage;
import com.bankcomm.util.BranchBankUtils;
import com.bankcomm.util.DownloadThread;
import com.rytong.tools.clienthello.ClientHello;
import com.rytong.tools.crypto.AESCipher;
import com.rytong.tools.datastorage.PackageManagerAndroid;
import com.rytong.tools.httpconnect.HttpManager;
import com.rytong.tools.httpconnect.WaitDialog;
import com.rytong.tools.ui.AtomParser;
import com.rytong.tools.ui.BaseView;
import com.rytong.tools.ui.Component;
import com.rytong.tools.ui.ComponentCopy;
import com.rytong.tools.utils.LPToastUtil;
import com.rytong.tools.utils.Utils;

/**
 * 管理用户信息
 * 
 * @author zhaobin
 * 
 * @date 2013.5.13
 */
public class UserManager {
	private HttpManager httpManager_;
	public PackageManagerAndroid pm_;
	private LPMid mid_;
	protected String requestStr;
	protected Activity activity_;
	public DataStorage data = null;
	
	/**
	 * 判断解压标志
	 */
	private String handUnZip = "";
	public UserManager(LPMid mid, HttpManager hm, PackageManagerAndroid pm,
			Activity activity) {
		httpManager_ = hm;
		pm_ = pm;
		mid_ = mid;
		activity_ = activity;
		
		handUnZip = "zip"+getClientVersion(activity);
	}

	private int msg = -1;
	/**
	 * 处理第一次请求 建立加密通道
	 */
	public void handleFirstRequest(final Activity activity,final Handler mHandler) {
		LPToastUtil.isBuildChannel = false;
		msg = -1;
		mid_.waitDialog_.addBgTask(new WaitDialog.Task(0) {
			@SuppressWarnings("unused")
			@Override
			public void run(WaitDialog dlg) throws Exception {
				if (!Utils.isConnectByNet()) {
					msg = 1;
					throw new Exception("网络未连接，请检查您的网络设置。");
				}
				ClientHello hello = new ClientHello(activity,
						ConfigManager.SERVER_URI, mid_.midletVersion_,
						ConfigManager.CLIENT_HELLO,
						ConfigManager.CLIENT_KEY_EXCHANGE,
						ConfigManager.CLIENT_FACILITY_HELLO, Utils.CERTIFICATE,
						"");
				requestStr = ClientHello.getText();
				verifyAppRight(requestStr);
			}

			public void onSuccess(WaitDialog dlg) {
				Utils.printOutToConsole("----reply----" + requestStr);
				/**
				 * 解析建完加密信道后返回的报文
				 */
				LPMid.getInstance().um_.data.initUpdateJson(requestStr);
				initAndDownloadOfflineResources(activity);
//				mHandler.sendEmptyMessage(1000);
//				LPToastUtil.isBuildChannel = true;
			}

			public void onFailure(WaitDialog dlg) {
				LPToastUtil.isBuildChannel = false;
				
				if(msg == 3){
					activity.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							exitSystem(getErrMsg(), activity);
						}
					});
					return;
				}
				
				String errorMsg = "";
				if(msg == 1){
					errorMsg = "网络未连接，请检查您的网络设置。";
				}else{
					errorMsg = "您的网络不给力，请重试";
				}
				Message message = new Message();
				message.what = 1001;
				message.obj = errorMsg;
				mHandler.sendMessage(message);
//				activity.runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						Toast.makeText(activity, getErrMsg(), Toast.LENGTH_SHORT).show();
//						String errorMsg = getErrMsg();
//						if(errorMsg.contains(".NullPoi")){
//							errorMsg = Utils.getConfigStringFormAsset(activity, "httpError");
//						}
//						exitSystem(errorMsg, activity);
//					}
//				});
			}
		});
	}

	/**
	 * 对返回的结果做验证处理
	 * 
	 * @param result
	 * @throws Exception
	 */
	public void verifyAppRight(String result) throws Exception {
		if (null == requestStr || "".equalsIgnoreCase(requestStr)) {
			msg = 2;
			throw new Exception("无法连接服务器！");
		}

		if (result.indexOf("<error") != -1) {
			String errorType = Utils.getXMLResponseAttribute(result, "type=\"",
					0, Utils.MATCH);
			String errorMsg = Utils.getXMLResponseAttribute(result,
					"string=\"", 0, Utils.MATCH);
			// 防篡改验证
			if (null != errorType && errorType.equalsIgnoreCase("verifyFail")) {
				msg = 3;
				throw new Exception(errorMsg);
			}
		}
	}

	/**
	 * 初始化并下载离线资源文件
	 * @param activity
	 * @param mHandler
	 */
	protected void initAndDownloadOfflineResources(final Activity activity) {
		//判断是否是首次使用客户端
		int index = 1;
		String isfirst = PackageManagerAndroid.ANDROIDDB.get(PackageManagerAndroid.ISFIRST_DB);
		if (null != isfirst && !"".equalsIgnoreCase(isfirst)) {
			index = Integer.parseInt(isfirst);
			index++;
		}
		isfirst = String.valueOf(index);
		PackageManagerAndroid.ANDROIDDB.save(PackageManagerAndroid.ISFIRST_DB,isfirst);

		/**
		 * 从ewp取出客户端更新信息 ---start--- 三种状态: must--强制更新; option--非强制更新;no--无需更新
		 * 
		 */
		try {
			JSONObject replyJO = new JSONObject(requestStr);
			if(null != replyJO){
				final String status = replyJO.getString("updateStatus");
				final String url = replyJO.getString("downloadfrom");
				if(null != status && !"".equalsIgnoreCase(status)){
					if(!status.equals("NO") && null != url && !"".equalsIgnoreCase(url)){
						activity.runOnUiThread(new Runnable() {
							@Override
							public void run() {
								alertDownLoadDialog(activity,status, url);
							}
						});
						return;
					}
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			Utils.printException(e);
		}
		// 下载离线资源
		LPToastUtil.isUpdateOffline = false;
		BaseView.OFFSTORED.downloadOfflineResource(ConfigManager.SERVER_URI);
	}

	/**
	 * 解压本地离线资源文件
	 * 
	 * handUnZip确定每次版本更新时都要解压离线文件
	 */
	public void unzipLocalOfflineResources(){
		String isUnZip = PackageManagerAndroid.ANDROIDDB.get("hadUnZip");
		// 解压本地资源
		if (null == isUnZip || "".equalsIgnoreCase(isUnZip) || !isUnZip.equalsIgnoreCase(handUnZip)) {
//			BaseView.OFFSTORED.deleteAllLocalFile(BaseView.OFFSTORED.fileTemp);
			BaseView.OFFSTORED.unzipLocalFile("BCOM");
			PackageManagerAndroid.ANDROIDDB.save("hadUnZip", handUnZip);
		}
	}
	
	/**
	 * 获取客户端版本号
	 * */
	public String getClientVersion(Activity activity_) {
		PackageInfo packageInfo = null;
		try {
			packageInfo = activity_.getPackageManager().getPackageInfo(activity_.getPackageName(), PackageManager.GET_CONFIGURATIONS);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 登陆成功后，保存BankUserCode
	 * */
	public void saveBankUserCode(String bankUserCode) {
		if (null != bankUserCode) {
			PackageManagerAndroid.ANDROIDDB.save(
					PackageManagerAndroid.BANKUSERCODE_DB, bankUserCode);
		}
	}

	/**
	 * 读取BankUserCode
	 * */
	public String readBankUserCode() {
		return PackageManagerAndroid.ANDROIDDB
				.get(PackageManagerAndroid.BANKUSERCODE_DB);
	}

	/**
	 * 退出程序
	 * @param string
	 * @param act
	 */
	protected void exitSystem(String string, final Activity act) {
		new AlertDialog.Builder(act).setTitle("提示").setMessage(string)
				.setCancelable(false)
				.setNegativeButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// 停止程序开启的服务，保证程序退出后不会常驻内存
						((BaseView) act).exitSystem();
					}
				}).show();
	}

	/**
	 * 点击九宫格后，跳转进入EmpView
	 * 
	 * @param activity
	 * @param hashMap
	 *            channel
	 * */
	public void gotoEmpViewFromHome(final BaseViewCopy activity,final String link,final String tempbody){
		mid_.waitDialog_.addFgTask(activity, null, 0, 0, 0, new WaitDialog.Task(0) {

			Object result = null;
			@Override
			public void run(WaitDialog dlg) throws Exception {
				// TODO Auto-generated method stub
				String url = link;
				if(url.startsWith("local:")){
					result = Utils.getFileFromOffline(url.substring(6));
				}else{
					if(null != url && url.startsWith("/")){
						url = ConfigManager.SERVER_URI+url;
					}

					String cityValue="";
					String cityId = "";
	                String saveCity = PackageManagerAndroid.ANDROIDDB.get("city_select");
	                if(null != saveCity && !"".equalsIgnoreCase(saveCity)){
	                        String[] city =  saveCity.split("\\|");
	                        cityValue=city[1];
	                        cityId = city[0];
	                }
					
					//为每个频道传城市参数
					String body = "currentcity=" + Utils.escapeURIComponent(cityValue)
							+ "&currentcityId=" + cityId;
					body=body+"&"+tempbody;
					body=AESCipher.encrypt(body, AESCipher.clientKey_, AESCipher.clientIv_);
					result = httpManager_.sendPostRequest(url, body, this, null, null);

							// 对报文做解密处理
							if (null != result && !"".equalsIgnoreCase(String.valueOf(result))) {
								result = AESCipher.decrypt(String.valueOf(result),AESCipher.serverKey_,AESCipher.serverIv_);
							}
							Utils.printOutToConsole(result);
						}
					}

			@Override
			public void onSuccess(WaitDialog dlg) {
				// TODO Auto-generated method stub
				if(null != result && !"".equalsIgnoreCase(String.valueOf(result))){
					Utils.printOutToConsole("-------------MainHome----------"+result);
					Intent intent = new Intent();
					if(LPToastUtil.getInstance().isBranchBank){
						intent.setClass(activity, BCMBranchBankActivity.class);
					}else{
						intent.setClass(activity, EMPView.class);						
					}
					intent.putExtra("reply", String.valueOf(result));
					activity.startActivity(intent);
					if(activity instanceof BOCMainHome){
						((BOCMainHome)activity).handler.sendEmptyMessageDelayed(1,1000);						
					}
				}
				super.onSuccess(dlg);
			}

			@Override
			public void onFailure(WaitDialog dlg) {
				// TODO Auto-generated method stub
				super.onFailure(dlg);
				//mid_.alert(activity, this.getErrMsg(), false);
				activity.handleException(getErrMsg());
			}
		});
	}

	/**
	 * 跳转到EMPView
	 */
	public void doActionWithLink(BaseViewCopy activity,String link){
		if(null != link && !"".equalsIgnoreCase(link)){
			if(link.startsWith("/")){
				gotoEmpViewFromHome(activity,link,"");
			}else{
				dealWithLink(link,activity);
			}
		}
	}
	/**
	 *发送请求时，判断请求方式或者跳转方式 add by cheng.l 
	 * @param link
	 * @param activity
	 */
	public void dealWithLink(String link,BaseViewCopy activity){
		if(null != link && !"".equalsIgnoreCase(link)){
			link = link.trim();
			if(link.startsWith("/")){
				//发送请求
				String url = ConfigManager.SERVER_URI+link;
				sendHttpRequest(activity, url,null);
			}else if(link.startsWith("tel://")){
				//拨打电话
				Intent telIntent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + link.substring(6)));
				activity.startActivity(telIntent);
			}else if(link.startsWith("sms://")){
	        	Uri uri = Uri.parse("smsto:"+link.substring(6));
	        	Intent intent = new Intent(android.content.Intent.ACTION_SENDTO,uri);
	        	activity.startActivity(intent);
			}else if(link.startsWith("http://") || link.startsWith("https://")){
				//跳转浏览器
				activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
			}else if(link.startsWith("inner:")){
				Intent intent=new Intent(activity,BOCWebViewActivity.class);
				link=link.substring(6,link.length());
				intent.putExtra("url",link);
				activity.startActivity(intent);
			}
		}
		
	}
	
	/**
	 * 发送请求 ，例如，机票预定、火车票预定、电影票预定等
	 * @param activity
	 * @param url
	 */
	public void sendHttpRequest(final BaseViewCopy activity,final String url,final String body){
		mid_.waitDialog_.addFgTask(activity, null, 0, 0, 0, new WaitDialog.Task(0) {

			Object result = null;
			@Override
			public void run(WaitDialog dlg) throws Exception {
				// TODO Auto-generated method stub
				result = handleShouldAES(url,body,this);
			}

			@Override
			public void onSuccess(WaitDialog dlg) {
				// TODO Auto-generated method stub
				if(null != result){
					result = Utils.unescapeHTML(result.toString());
					result = Utils.insteadOfSpecillCharacter(result.toString(), true);
					if(LPToastUtil.getInstance().isBranchBank){
						result = BranchBankUtils.addBrAtEnd(BranchBankUtils.includeAloneAttribute(result.toString()));
					}
					AtomParser apc = new AtomParser(activity, AtomParser.ENTIRE);
					try {
						Utils.printOutToConsole("result--++--"+result);
						android.util.Xml.parse(((String)result).trim(), apc);
						//解析成功后压栈
						Component.ACTIONV.push((String)result);
						// 有可能解析的报文不含body标签，导致COMPONENT为null，此处加一个判断。
					} catch (SAXException e) {
						Utils.printException(e);
					} catch (Exception e){
						Utils.printException(e);
					}
					
					activity.runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							if(ComponentCopy.COMPONENT != null){
								((EMPView)ConfigManager.currentView_).setContentView(ComponentCopy.COMPONENT.getLPView());
							} 						
						}
					});
				}
				super.onSuccess(dlg);
			}

			@Override
			public void onFailure(WaitDialog dlg) {
				// TODO Auto-generated method stub
				super.onFailure(dlg);
				//mid_.alert(activity, this.getErrMsg(), false);
				activity.handleException(getErrMsg());
			}
		});
	}
	
	/**
	 * 是否进行AES加密
	 * @param url
	 * @param body
	 * @param task
	 * @return
	 * @throws Exception
	 */
	public String handleShouldAES(String url, String body, WaitDialog.Task task) throws Exception {

		String enCodeBody = body;
		// 等待EWP完善后加入
		if (url.indexOf("?") != -1) {
			int indexFirst=url.indexOf("?");
			String urlstr=url.substring(0, indexFirst);
			String bodystr="";
			if(url.length()>indexFirst)
			bodystr=url.substring(indexFirst+1,url.length());
			
			Utils.printOutToConsole(url+"  "+body);
			if(enCodeBody==null){
				enCodeBody=bodystr;
			}else{
				enCodeBody=enCodeBody + "&"+bodystr;
			}
//			String str[] = url.split("\\?");
//			url = str[0];
//			if (enCodeBody == null) {
//				enCodeBody = str[1];
//			} else if(str.length >= 2){
//				enCodeBody = enCodeBody + "&" + str[1];
//			}
			url=urlstr;
		}
		
		if(null != enCodeBody && enCodeBody.endsWith("&")){
			enCodeBody = enCodeBody.substring(0,enCodeBody.length()-1);
		}

		Utils.printOutToConsole("--UserManager--++url++" + url);
		Utils.printOutToConsole("--UserManager--++body++" + enCodeBody);
		if (url.indexOf("_s/") != -1 && enCodeBody != null
				&& !"".equals(enCodeBody)) {
			enCodeBody = (AESCipher.encrypt(enCodeBody, AESCipher.clientKey_,AESCipher.clientIv_)).trim();
			Utils.printOutToConsole("--UserManager--++加密body++"+ enCodeBody);
		}

		String replyRes = ((String) LPMid.getInstance().hm_.sendPostRequest(url, enCodeBody, task, null, null)).trim();
		Utils.printOutToConsole("--UserManager--++未解密报文++"+ replyRes);

		if (null != replyRes && url.indexOf("_s/") != -1) {
			replyRes = (AESCipher.decrypt(replyRes, AESCipher.serverKey_,AESCipher.serverIv_)).trim();
			Utils.printOutToConsole("--UserManager--++解密后报文++" + replyRes);
		}

		return replyRes;
	}

    /**
     * 由EWP后台调用的LUA方法，从交易页面跳转到首页
     * index:0-"我的首页"，1-"生活服务"，2-"金融服务"，3-"投资理财"
     * @param index add by cheng.l
     */
	public void backToHome(Activity activity , int index){
    	if(activity instanceof EMPView){
    		if(null != Component.ACTIONV){
    			Component.ACTIONV.clear();    			
    		}
    	}
    	//如果是从推送页面进入到EMPView那首页activity还没生成
    	if(LPMid.isPushActivity){
    		BOCPushMessage.gotoActivity(ConfigManager.currentView_);
    		LPMid.indexTab = index;
    	}else{
    		BCMHomeView.changeScrollTab(index);
    		BankcommApplication.getInstance().removeActivity(activity);
    		activity.finish();    		
    	}
	}

	/**
	 * 客户端版本提示更新
	 * @param status
	 * @param url
	 */
	void alertDownLoadDialog(final Activity activity,final String status, final String url) {
		//是否必须更新
		final boolean isMustUpdate = !status.equals("MUST") ? false:true;
		String cancelStr = "";
		if(isMustUpdate){
			cancelStr = "退出";
		}else{
			cancelStr = "取消";
		}
		
		new AlertDialog.Builder(activity).setTitle("版本更新")
			.setMessage("当前存在新版本，是否更新?")
			.setPositiveButton("确定", new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					downLoadApk(activity,url);
				}
			}).setNegativeButton(cancelStr, new OnClickListener() {
				
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					if(isMustUpdate){
						((BaseView)activity).exitSystem();
					}else{
						BaseView.OFFSTORED.downloadOfflineResource(ConfigManager.SERVER_URI);
					}
				}
			}
		).show();
	}

	/**
	 * 下载APK
	 * @param downUrl
	 */
	public void downLoadApk(Activity activity,String downUrl) {
		Utils.printOutToConsole("下载URL:" + downUrl);
		if (!downUrl.startsWith(Utils.SERVER_URI)) {
			if (downUrl.startsWith("/")) {
				downUrl = Utils.SERVER_URI.concat(downUrl);
			}
		}
		BaseViewCopy act = (BaseViewCopy) activity;
		if (act.downloadThread == null) {
			act.downloadThread = new DownloadThread(act);
		}
		act.downloadThread.setApkDownload(downUrl);
		act.downloadThread.downLoad();
	}

	/**
	 * 跳转到位置服务
	 * @param bv
	 * @param id
	 */
	public void jumpToLocationService(BaseViewCopy bv, String id) {
		if (id.equals("red_shops")) {
			Intent intent = new Intent();
			intent.setClass(bv, BOC_SpecialShop_main_Activity.class);
			intent.putExtra("str", id);
			bv.startActivity(intent);
			return;
		}
		Intent intent = new Intent();
		intent.setClass(bv, LocationServiceActivity.class);
		intent.putExtra("str", id);
		bv.startActivity(intent);
	}

	/**
	 * 跳转到最红商铺
	 * @param bv
	 * @param id
	 */
	public void jumpToRedShop(final BaseViewCopy bv, final String id) {
		mid_.waitDialog_.addFgTask((Activity) bv, null, 0, 0, 0,
				new WaitDialog.Task(0) {
					public void run(WaitDialog dlg) throws Exception {
						String url = ConfigManager.SERVER_URI
								+ ConfigManager.MAP_GET_CITY;
						String reply = mid_.hm_.sendRequest(url, this);
						Utils.printOutToConsole(reply);
						JSONObject replyJO = new JSONObject(reply);
						mid_.initCityData(replyJO.getString("merchantRegion"));
						mid_.initMostPopData(replyJO.getString("merchantTypes"));
					};

					public void onSuccess(WaitDialog dlg) {
						super.onSuccess(dlg);
						jumpToLocationService(bv, id);
					};

					public void onFailure(WaitDialog dlg) {
						super.onFailure(dlg);
						bv.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								bv.handleException(getErrMsg());
							}
						});
					};
				});
	}

	/**
	 * 复制ASSERT大智慧APK到SD卡,并安装
	 */
	String FILENAME;
	File file;

	public void copydzhapk(Activity act) {
		boolean ismemory = false;
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			FILENAME = Environment.getExternalStorageDirectory() + "/Dzh.apk";
		} else {
			FILENAME = act.getApplicationContext().getFilesDir()
					.getAbsolutePath()
					+ "/Dzh.apk";
			ismemory = true;
		}
		Utils.printOutToConsole("the direct where copy to :" + FILENAME);
		try {
			file = new File(FILENAME);
			OutputStream out = new FileOutputStream(file);
			InputStream in = act.getAssets().open("Dzh.apk");
			int length = -1;
			byte[] buf = new byte[1024];
			while ((length = in.read(buf)) != -1) {
				out.write(buf, 0, length);
			}
			out.flush();
			in.close();
			out.close();
			if (ismemory == true) {
				String command = "chmod 777 " + FILENAME;
				Runtime runtime = Runtime.getRuntime();
				runtime.exec(command);
				Utils.printOutToConsole("ismemory :" + ismemory);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 安装大智慧APK
	 */
	public void installAPK(Activity act) {
		try{
		Intent intent = new Intent();
		intent.setAction(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
		act.startActivity(intent);
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * 打开大智慧Activity
	 */
	public void startDzhActivity(Activity act,String packageName){
		Intent it=new Intent();
		it.setClassName(packageName, "com.android.dazhihui.dzh.dzh");
		act.startActivity(it);
		deleteDzh(act);
	}
	/**
	 * 删除大智慧的APK
	 */
	public void deleteDzh(Activity act){
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			FILENAME =Environment.getExternalStorageDirectory()+ "/Dzh.apk";
		} else {
			FILENAME = act.getApplicationContext().getFilesDir()
					.getAbsolutePath()
					+ "/Dzh.apk";
		}
		file = new File(FILENAME);
		if(file.exists()){
		file.delete();
		}
	}
	
	/**
	 * 通过百度地图获取定位信息并做跳转
	 * @param act
	 * @param locationServices
	 * @param url
	 * @param id
	 */
	public void jumpWithLocation(final BaseViewCopy act,final BaiduLocation locationServices,final String id ,final String url,final String name){
		new WaitDialog().showProgressdialog(act);
		locationServices.getLocation(act, new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 2001:
					// 定位成功
					Bundle bundle = msg.getData();
					gotoJumpWithLocation(act,id,url,bundle,name,true);
					break;
				case 3001:
					// 定位失败
					gotoJumpWithLocation(act,id,url,null,name,false);
					break;
				}
			}
		});
	}
	
	/**
	 * 获取定位成功或者失败处理
	 * @param bv
	 * @param id
	 * @param url
	 * @param bundle 定位信息
	 * @param isTrue 获取定位成功或者失败
	 */
	private void gotoJumpWithLocation(BaseViewCopy bv,String id,String url,Bundle bundle,String name,boolean isTrue){
		if(id.equalsIgnoreCase("native")){
			String body = "";
			//分行
			if (isTrue && null != bundle) {
				String currentLon = String.valueOf(bundle.getDouble("lon"));
				String currentLat = String.valueOf(bundle.getDouble("lat"));
				body = "longitude=%s&latitude=%s";
				body = String.format(body, currentLon, currentLat);
			}else{
				body = "longitude=&latitude=";
			}
			gotoEmpViewFromHome(bv, url, body);
		}else if(id.equalsIgnoreCase("traffic_e_drive")){
			url = "http://h5.edaijia.cn/bcm/index.html";
			url = url.concat("?version=android");
			if(isTrue && null != bundle){
				url = url.concat("&lng=").concat(String.valueOf(bundle.getDouble("lon")))
					.concat("&lat=").concat(String.valueOf(bundle.getDouble("lat")));
			}else{
				url = url.concat("&lng=&lat=");
			}
			
			Intent intent=new Intent(bv,BOCWebViewActivity.class);
			intent.putExtra("url",url);
			intent.putExtra("title", name);
			bv.startActivity(intent);
			WaitDialog.cancelProgressBar(bv);
		}
	}
}
